package interfaz;

import clases.ClsDatabase;
import clases.ClsMetodos;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author MK
 */
public class dlgInsumos2 extends javax.swing.JDialog {

    private ClsMetodos metodos = new ClsMetodos();
    private ClsDatabase bd = new ClsDatabase();
    DefaultComboBoxModel modelCboTipoInsumo = new DefaultComboBoxModel();
    DefaultComboBoxModel modelCboIndice = new DefaultComboBoxModel();
//    String idString=null;
    /**
     * Creates new form dlgInsumos2
     *
     * @param parent
     * @param modal
     */
    int c1, c2;

    public dlgInsumos2(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        _iniciar();//Iniciamos algunos componentes por defecto...

    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public final void _iniciar() {
        setLocationRelativeTo(null);
        metodos._iconJDialog(this);
        alinear_tabla();
        txtBuscar.setText("");
        txtBuscar.requestFocus();
        c1 = 0;
        c2 = 0;
        metodos.comboboxLlenarMas(cboTipoInsumo, modelCboTipoInsumo, "SELECT idinsumo_tipo,nombre FROM insumo_tipo");
        metodos.comboboxLlenarMas(cboIndice, modelCboIndice, "SELECT idinsumo_indice,concat(idinsumo_indice,'-',descripcion) FROM insumo_indice");
        _cargarDatosTable();

        c1 = 1;
        c2 = 1;
        metodos.tablaLongitudColumnas(tblInsumos, new int[]{40, 400, 60, 40, 60, 0, 0, 250});
        metodos.tablaOcultarcolumnas(tblInsumos, new int[]{5, 6});
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public void alinear_tabla() {
        //izquierda
        DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
        modelocentrar.setHorizontalAlignment(SwingConstants.RIGHT);
        tblInsumos.getColumnModel().getColumn(2).setCellRenderer(modelocentrar);
    }

    public void seleccionar_base(String valor) {
        metodos.seleccionar_tabla(tblInsumos, 0, valor);
    }

    public void _cargarDatosTable() {
        String nombreBuscar = txtBuscar.getText().toString();
        metodos.tablaLlenaSql_defecto(tblInsumos,
                "concat(i.idinsumo),i.nombre,i.precio,t.abreviatura,u.simbolo,i.estado,i.idinsumo_indice,concat(ii.idinsumo_indice,'-',ii.descripcion)  ",
                "FROM insumo i,insumo_tipo t,unidad u,insumo_indice ii "
                + "WHERE t.idinsumo_tipo=i.idinsumo_tipo and u.idunidad=i.idunidad and i.idinsumo_indice=ii.idinsumo_indice and i.nombre like '%" + nombreBuscar + "%'  and i.idinsumo_tipo like '" + modelCboTipoInsumo.getElementAt(cboTipoInsumo.getSelectedIndex()) + "%'  "
                + "and ii.idinsumo_indice like '" + modelCboIndice.getElementAt(cboIndice.getSelectedIndex()) + "%' "
                + "ORDER BY t.orden asc, i.nombre asc");
        metodos.tablaRedondea(tblInsumos, new int[]{2});
    }

    //___________________________________________________________________________________ Soy una barra separadora :)
    public void EliminarInsumo() {
        int fila = tblInsumos.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {
            //Confirmamos la eliminacion
            if (JOptionPane.showConfirmDialog(null, "Está seguro que desea eliminar el Insumo seleccionado", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                String id = tblInsumos.getValueAt(fila, 0).toString();
                boolean seRepite = bd.verif_repite("SELECT idinsumo FROM partida_detalle WHERE idinsumo='" + id + "'");
                if (!seRepite) {
                    seRepite = bd.verif_repite("SELECT idinsumo FROM partida_base_detalle WHERE idinsumo='" + id + "'");
                    if (!seRepite) {
                        boolean seElimino = bd.delete("insumo", "idinsumo='" + id + "'");
                        if (seElimino) {
                            _cargarDatosTable();
                            //JOptionPane.showMessageDialog(null, "Se elimino el Insumo con exito");
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "No se puede eliminar este Insumo porque ya está siendo utilizado");
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "Seleccione un Insumo");
        }
    }
//___________________________________________________________________________________ Soy una barra separadora :)

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlInsumos = new javax.swing.JPanel();
        pnlTablaInsumo = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblInsumos = new javax.swing.JTable();
        btnQuitar_Unidad = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        btnEditar1 = new javax.swing.JButton();
        btnAgregar_Unidad = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtBuscar = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cboIndice = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        cboTipoInsumo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Insumos");

        pnlTablaInsumo.setBackground(new java.awt.Color(225, 235, 247));
        pnlTablaInsumo.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tblInsumos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Cód.", "Descripción", "Precio", "Tipo", "Unidad", "Estado", "IDIndice", "Índice"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblInsumos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblInsumos.getTableHeader().setReorderingAllowed(false);
        tblInsumos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblInsumosMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tblInsumos);

        pnlTablaInsumo.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 94, 938, 401));

        btnQuitar_Unidad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/borrar.png"))); // NOI18N
        btnQuitar_Unidad.setText("Eliminar");
        btnQuitar_Unidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitar_UnidadActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(btnQuitar_Unidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(226, 506, 112, -1));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/salir.png"))); // NOI18N
        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(846, 506, 102, -1));

        btnEditar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/editar.png"))); // NOI18N
        btnEditar1.setText("Editar");
        btnEditar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditar1ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(btnEditar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(118, 506, 90, -1));

        btnAgregar_Unidad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/agregar.png"))); // NOI18N
        btnAgregar_Unidad.setText("Crear");
        btnAgregar_Unidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregar_UnidadActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(btnAgregar_Unidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 506, 90, -1));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar"));
        jPanel1.setOpaque(false);
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });
        jPanel1.add(txtBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(67, 27, 210, -1));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Nombre:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 27, -1, 25));

        cboIndice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboIndice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboIndiceActionPerformed(evt);
            }
        });
        jPanel1.add(cboIndice, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 27, 260, -1));

        jLabel11.setText("Índice unificado:");
        jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 30, 90, -1));

        cboTipoInsumo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboTipoInsumo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboTipoInsumoActionPerformed(evt);
            }
        });
        jPanel1.add(cboTipoInsumo, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 27, 170, -1));

        jLabel9.setText("Tipo insumo:");
        jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 30, -1, -1));

        pnlTablaInsumo.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 930, 70));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pnlTablaInsumo.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 330));

        javax.swing.GroupLayout pnlInsumosLayout = new javax.swing.GroupLayout(pnlInsumos);
        pnlInsumos.setLayout(pnlInsumosLayout);
        pnlInsumosLayout.setHorizontalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlInsumosLayout.createSequentialGroup()
                .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 969, Short.MAX_VALUE)
                .addGap(2, 2, 2))
        );
        pnlInsumosLayout.setVerticalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblInsumosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblInsumosMouseClicked
        if (evt.getClickCount() == 2) {
            dlg_NewInsumo dialogN = new dlg_NewInsumo(new javax.swing.JFrame(), true, this, tblInsumos);

            dialogN.Editar();
        }
    }//GEN-LAST:event_tblInsumosMouseClicked

    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        _cargarDatosTable();
    }//GEN-LAST:event_txtBuscarKeyReleased

    private void btnAgregar_UnidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregar_UnidadActionPerformed
        dlg_NewInsumo dialogN = new dlg_NewInsumo(new javax.swing.JFrame(), true, this, tblInsumos);
        dialogN.Nuevo();

        dialogN.setVisible(true);
    }//GEN-LAST:event_btnAgregar_UnidadActionPerformed

    private void btnEditar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditar1ActionPerformed
        dlg_NewInsumo dialogN = new dlg_NewInsumo(new javax.swing.JFrame(), true, this, tblInsumos);

        dialogN.Editar();
    }//GEN-LAST:event_btnEditar1ActionPerformed

    private void btnQuitar_UnidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitar_UnidadActionPerformed
        EliminarInsumo();
    }//GEN-LAST:event_btnQuitar_UnidadActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cboTipoInsumoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboTipoInsumoActionPerformed
        if (c1 == 1) {
            _cargarDatosTable();
        }
    }//GEN-LAST:event_cboTipoInsumoActionPerformed

    private void cboIndiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboIndiceActionPerformed
        if (c1 == 1) {
            _cargarDatosTable();
        }
    }//GEN-LAST:event_cboIndiceActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgInsumos2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgInsumos2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgInsumos2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgInsumos2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgInsumos2 dialog = new dlgInsumos2(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar_Unidad;
    private javax.swing.JButton btnEditar1;
    private javax.swing.JButton btnQuitar_Unidad;
    private javax.swing.JComboBox cboIndice;
    private javax.swing.JComboBox cboTipoInsumo;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane3;
    public javax.swing.JPanel pnlInsumos;
    private javax.swing.JPanel pnlTablaInsumo;
    private javax.swing.JTable tblInsumos;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
